<template>
  <div class="list-content wrap-inspection-analysis">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
      <!-- <el-form-item v-if="isMuilUnitUser">
        <el-select filterable @change="getUnitStatistic()" v-model="formInline.orgIds" placeholder="请选择业主单位">
          <el-option
            v-for="item in orgOptionsAll"
            :key="item.organizationId"
            :label="item.shortName"
            :value="item.organizationId">
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item>
        <el-select class="none-right-bd" @change="getData(1)" v-model="formInline.queryTimeType" style="width:120px;">
          <el-option label="按开始时间" value="1"></el-option>
          <el-option label="按结束时间" value="2"></el-option>
        </el-select>
        <el-date-picker
          class="none-left-bd"
          v-model="formInline.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="util.intTimePickerOptions()"
          @change="getData()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-select filterable clearable placeholder="全部标签" @change="getData()" v-model="formInline.labelId">
          <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select filterable clearable @change="getData()" v-model="formInline.planId" placeholder="全部计划">
          <el-option v-for="item in planOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="form-search-btn" type="primary" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row v-loading="loading" class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
      <el-col :span="4">
        <div class="item-wrap" @click="openRecord('')">
          <div class="item-content">
            <p class="item-value color-4">{{ staticObj.total }}</p>
            <p class="item-title bold">任务总数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="openRecord(2)">
          <div class="item-content">
            <p class="item-value color-3">{{ staticObj.examinedNum}}</p>
            <p class="item-title bold">完成数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="openRecord(1)">
          <div class="item-content">
            <p class="item-value color-1">{{ staticObj.unExaminedNum }}</p>
            <p class="item-title bold">未完成数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="openRecord(-1)">
          <div class="item-content">
            <p class="item-value color-2">{{ staticObj.noOkPointNum }}</p>
            <p class="item-title bold">发现不合格点位次数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" style="cursor:default;">
          <div class="item-content">
            <p class="item-value">{{ Math.round((staticObj.examinedNum||0)*100/(staticObj.total||1)) }}%</p>
            <p class="item-title bold">任务完成率</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row v-loading="loading">
      <el-col :span="24" v-if="isMuilUnitUser&&unitData.length>0" style="margin-bottom:20px;">
        <div class="grid-content">
          <div class="d-flex ai-center">
            <div class="chart-head">
              <span>单位完成度排名</span>
            </div>
            <el-radio-group v-model="sortType" style="margin-left:20px;" @change="handleSortChange">
              <el-radio-button :label="1">降序</el-radio-button>
              <el-radio-button :label="2">升序</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-wrap">
            <el-checkbox v-model="showBarValue" @change="drawChart">显示数值</el-checkbox>
            <div id="finishRate_inspect" class="chart-content" style="height: 500px;" :style="{ width:chartWidth }"></div>
          </div>
        </div>
      </el-col>
      <el-col :span="24">
        <div class="grid-content">
          <div class="d-flex ai-center">
            <div class="chart-head">员工完成数排名</div>
            <span style="margin:0 10px 0 20px;">按完成任务数</span>
            <el-radio-group v-model="sortType2" @change="handleUserSortChange">
              <el-radio-button :label="1">降序</el-radio-button>
              <el-radio-button :label="2">升序</el-radio-button>
            </el-radio-group>
          </div>
          <el-table
            :data="tableData"
            ref="mainTable"
            :row-class-name="tableRowClassName"
            style="margin-top:10px;width: 100%"
          >
            <el-table-column label="排名" width="80" align="center">
              <template v-slot="sc">{{sc.$index+1}}</template>
            </el-table-column>
            <el-table-column prop="name" label="员工名称" align="center">
              <template v-slot="sc">
                {{sc.row.name}}
                <el-tag v-if="sc.row.account==userinfo.accountName" style="margin-left:5px;">我</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="taskNum" label="总任务" align="center"></el-table-column>
            <el-table-column prop="checkNum" label="完成任务" align="center"></el-table-column>
            <el-table-column prop="isNotPointTaskNum" label="发现不合格点位" align="center"></el-table-column>
            <el-table-column prop="pointNum" label="点位次数" align="center"></el-table-column>
            <el-table-column prop="totalTime" label="总耗时" :formatter="formatDuration" align="center"></el-table-column>
            <el-table-column prop="avgTime" label="任务平均耗时" :formatter="formatDuration" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button @click="openRecord(1,scope.row.account)" type="text" size="small">查看未完成任务</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { qnToken } from '@/api/api'
import {
  getInspectPlanList,
  getPointLabelList,
  getOrgInspectCompleteness,
  getPersonInspectRank,
  getInspectTaskStatistic,
} from '@/api/inspectx'
import { getOrgList } from '@/api/org'
import util from '@/utils/util'
import { mapState, mapGetters, mapMutations } from 'vuex'

export default {
  name: 'InspectionAnalysis',
  props: ['param'],
  data() {
    return {
      labelList: [],
      tableData: [],
      freashStaticFlag: 0,
      formInline: {
        queryTimeType: '1',
        orgIds: '',
        time: '',
        planId: '',
        labelId: '',
      },
      util: util,
      planOptions: [],
      loading: false,
      colorList: [
        '#70bbea',
        '#5c90d2',
        '#a58ad4',
        '#f3b75e',
        '#ea4f63',
        '#16adc4',
        '#9BCA63',
        '#FAD860',
        '#F3A43B',
        '#60C0DD',
        '#D7504B',
        '#C6E579',
        '#F4E001',
        '#F0805A',
        '#26C0C0',
      ],
      sortType: 1,
      sortType2: 1,
      staticObj: {},
      unitData: [],
      showBarValue: false,
    }
  },
  computed: {
    ...mapState(['orgOptions', 'userinfo']),
    ...mapGetters([
      'isMuilUnitUser',
      'userOrgId',
      'userOrgIds',
      'orgOptionsAll',
      'userFullOrgIds',
    ]),
    chartWidth() {
      return this.unitData.length <= 20
        ? 'auto'
        : this.unitData.length * 90 + 'px'
    },
  },
  created: function () {
    //默认一个月
    let end = new Date()
    let start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    this.formInline.time = [
      util.ilinkTimeformat.format(start, 'yyyy-MM-dd ') + '00:00:00',
      util.ilinkTimeformat.format(end, 'yyyy-MM-dd ') + '23:59:59',
    ]
    this.getPointLabelList()
    getInspectPlanList({
      queryType: 0,
      orgIds: this.userFullOrgIds,
    }).then((data) => {
      if (data.data && data.data.length > 0) {
        this.planOptions.push.apply(this.planOptions, data.data)
        // this.formInline.planId = data.data[0].id
      }
      this.getData()
    })
  },
  methods: {
    ...mapMutations(['setRefreshInspectTask']),
    tableRowClassName({ row }) {
      return row.account == this.userinfo.accountName ? 'is-myself' : ''
    },
    handleUserSortChange() {
      this.tableData.reverse()
    },
    getData() {
      if (this.isMuilUnitUser) {
        this.getUnitStatistic()
      }
      this.getPersonStatistic()
      this.getInspectTaskStatistic()
    },
    getPointLabelList() {
      getPointLabelList({ type: 1 }).then((res) => {
        this.labelList = res.data || []
      })
    },
    openRecord(result = 1, account = '') {
      let { queryTimeType, time, planId, labelId } = this.formInline
      this.setRefreshInspectTask(true)
      this.$router.push({
        name: 'inspectRecord',
        params: {
          account,
          result,
          queryTimeType,
          time,
          planId,
          labelId,
          status: '',
        },
      })
    },
    handleSortChange() {
      this.drawChart()
    },
    drawChart() {
      let data = this.sortType == 1 ? this.unitData : this.unitDataAsc
      let xData = []
      let yData = []
      data.forEach((obj) => {
        yData.push(Math.round(obj.checkPercent * 100))
        xData.push(obj.orgName)
      })
      //画图
      let option_echart = {
        title: {
          textStyle: { color: '#999', fontSize: '14' },
          y: 'left',
          left: '35',
          top: '0',
          text: '完成率',
        },
        grid: {
          left: '55px',
          right: '20px',
          bottom: '80px',
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let { name, value, dataIndex } = params[0]
            return `${name}<br>第${dataIndex + 1}位<br>完成率${value}%`
          },
        },
        xAxis: {
          type: 'category',
          axisTick: { show: false },
          axisLine: {
            show: true,
            lineStyle: {
              color: 'rgba(105, 115, 125, 0.3)',
              width: 1, //这里是为了突出显示加上的
              type: 'dotted',
            },
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333',
              fontSize: 14,
            },
            interval: 0,
            rotate: xData.length > 10 ? 45 : 0,
          },
          data: xData,
        },
        yAxis: {
          type: 'value',
          axisTick: { show: false },
          axisLine: {
            show: true,
            lineStyle: {
              color: 'rgba(105, 115, 125, 0.3)',
              width: 1, //这里是为了突出显示加上的
              type: 'dotted',
            },
          },
          axisLabel: {
            formatter: function (value) {
              return value ? value + '%' : 0
            },
            show: true,
            padding: [0, 5, 0, 0],
            textStyle: {
              color: '#999',
              fontSize: 14,
            },
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(105, 115, 125, 0.3)',
              width: 1, //这里是为了突出显示加上的
              type: 'dotted',
            },
          },
          max: 100,
          min: 0,
        },
        series: [
          {
            name: '完成率',
            type: 'bar',
            smooth: true,
            symbol: 'circle',
            symbolSize: 0,
            barMaxWidth: 30,
            itemStyle: {
              color: '#67C23A',
            },
            label: {
              show: this.showBarValue,
              position: 'top',
              distance: 5,
              color: '#333',
              formatter: '{c}%',
            },
            data: yData,
          },
        ],
      }
      this.$echarts
        .init(document.getElementById('finishRate_inspect'))
        .setOption(option_echart, true)
    },
    getUnitStatistic() {
      if (!this.isMuilUnitUser) return
      this.loading = true
      getOrgInspectCompleteness(this.getCondition()).then((data) => {
        this.loading = false
        // for (var i = 0; i < 20; i++) {
        //   data.data.push({ orgName: '单位' + i, checkPercent: i / 100 })
        // }
        this.unitData = data.data
        this.unitDataAsc = [].concat(data.data).reverse()
        this.$nextTick(() => {
          this.drawChart()
        })
      })
    },
    getPersonStatistic() {
      let params = this.getCondition()
      delete params.status
      getPersonInspectRank(params).then((data) => {
        this.tableData = data.data
      })
    },
    formatDuration(row, col, val) {
      return val
        ? util
            .getTimeDuration(parseInt(val / 1000))
            .splice(0, 2)
            .map((m) => {
              return m.value + m.unit
            })
            .join('')
        : '-'
    },
    getInspectTaskStatistic() {
      getInspectTaskStatistic(this.getCondition()).then((res) => {
        this.staticObj = res.data
      })
    },
    getCondition() {
      let { queryTimeType, time, planId, labelId } = this.formInline
      return {
        orgIds: this.userFullOrgIds,
        planId,
        labelId,
        queryTimeType,
        startTime: time ? time[0].split(' ')[0] + ' 00:00:00' : '',
        endTime: time ? time[1].split(' ')[0] + ' 23:59:59' : '',
      }
    },
  },
}
</script>
<style lang="scss">
.wrap-inspection-analysis {
  .is-myself {
    background: #f0f9eb;
  }
  .chart-wrap {
    position: relative;
    .el-checkbox {
      position: absolute;
      top: 0;
      right: 20px;
      z-index: 1;
    }
  }
  .none-right-bd {
    .el-input__inner {
      border-right: none;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    .chart-head {
      height: 25px;
      line-height: 25px;
      font-size: 18px;
      font-weight: 500;
      color: rgba(68, 107, 222, 1);
      -webkit-text-stroke: 1px rgba(68, 107, 222, 1);
      text-stroke: 1px rgba(68, 107, 222, 1);
    }
    .chart-content {
      margin-top: 20px;
      height: 350px;
      width: 100%;
    }
  }
}
</style>